#include "foreach.hpp"
#include "string_utils.hpp"
#include "terrain.hpp"
#include "wml_node.hpp"
#include "wml_utils.hpp"

namespace hex {

namespace {
std::map<std::string, terrain_ptr> terrains;
int next_overlay_order = 1;
}

void terrain::init(wml::const_node_ptr node)
{
	FOREACH_WML_CHILD(terrain_node, node, "terrain") {
		terrain_ptr t(new terrain(terrain_node));
		terrains[t->id()] = t;
	}
}

const_terrain_ptr terrain::get(const std::string& key)
{
	std::map<std::string, terrain_ptr>::const_iterator itor = terrains.find(key);
	if(itor != terrains.end()) {
		return itor->second;
	} else {
		return const_terrain_ptr();
	}
}

terrain::terrain(wml::const_node_ptr node)
  : id_(node->attr("id")), name_(node->attr("name")), overlay_order_(next_overlay_order++), base_(game::base_terrain::get(node->attr("base")))
{
	if(node->has_attr("underlying")) {
		underlying_ = get(node->attr("underlying"));
	}

	foreach(const std::string& t, util::split(node->attr("image"))) {
		textures_.push_back(graphics::texture::get("/terrain/" + t));
	}
}

const std::vector<graphics::texture>& terrain::get_textures() const
{
	return textures_;
}

}
